#include "include/logger.hpp"

#include <filesystem>
#include <iostream>

namespace common {

std::shared_ptr<spdlog::logger> Logger::s_logger;
bool Logger::s_initialized = false;

void Logger::init(spdlog::level::level_enum log_level,
                  const std::string& log_filename, size_t max_size,
                  size_t max_files) {
    if (s_initialized) {
        return;
    }

    try {
        // 确保日志目录存在
        auto path = std::filesystem::path(log_filename).parent_path();
        if (!path.empty() && !std::filesystem::exists(path)) {
            std::filesystem::create_directories(path);
        }

        // 创建控制台日志接收器
        auto console_sink =
            std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
        console_sink->set_level(log_level);
        console_sink->set_pattern(
            "[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [thread %t] %v");

        // 创建文件日志接收器（循环覆盖）
        auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
            log_filename, max_size, max_files);
        file_sink->set_level(log_level);
        file_sink->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [thread %t] %v");

        // 创建组合日志器
        std::vector<spdlog::sink_ptr> sinks{console_sink, file_sink};
        s_logger = std::make_shared<spdlog::logger>("main", sinks.begin(),
                                                    sinks.end());
        s_logger->set_level(log_level);
        s_logger->flush_on(spdlog::level::err);

        // 设置为默认日志器
        spdlog::set_default_logger(s_logger);
        spdlog::flush_every(std::chrono::seconds(3));

        s_initialized = true;

        // LOG_INFO("日志系统初始化成功，日志级别: {}, 日志文件: {}",
        //          spdlog::level::to_string_view(log_level), log_filename);
    } catch (const std::exception& e) {
        std::cerr << "日志系统初始化失败: " << e.what() << std::endl;
        // 创建一个仅控制台的日志器作为备用
        s_logger = spdlog::stdout_color_mt("console");
        s_initialized = true;
    }
}

std::shared_ptr<spdlog::logger>& Logger::getLogger() {
    if (!s_initialized) {
        init();  // 使用默认参数初始化
    }
    return s_logger;
}

}  // namespace common